package cn.matezk.cloud.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.matezk.cloud.dto.SecretKeyDto;
import cn.matezk.cloud.model.DeviceBind;
import cn.matezk.cloud.model.SecretKey;
import cn.matezk.cloud.service.ISecretKeyService;
import cn.matezk.cloud.vo.SecretKeyVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = {"open", "secretKey"})
public class SecretKeyController {
    private static final String BASE_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789";

    @Autowired
    private ISecretKeyService secretKeyService;

    @GetMapping(value = {"appKey", "selector"})
    public List<JSONObject> appKey() {
        List<JSONObject> ret = new ArrayList<>();
        List<SecretKey> keys = secretKeyService.selectAll();
        keys.forEach(k->ret.add(JSONUtil.createObj()
                    .set("label", String.format("%s(%s)", k.getCustomer(), k.getAppKey()))
                    .set("value", k.getAppKey())));
        return ret;
    }

    @GetMapping
    public PageInfo<SecretKeyVo> query(SecretKeyDto secretKeyDto) {
        return secretKeyService.query(secretKeyDto);
    }

    @PutMapping()
    public SecretKey save(@RequestBody SecretKey secretKey) {
        Assert.hasLength(secretKey.getAppKey(), "appKey不能为空");
        Assert.hasLength(secretKey.getCustomer(), "客户不能为空");
        secretKey.setId(IdUtil.fastSimpleUUID());
        secretKey.setSecret(RandomUtil.randomString(BASE_STRING,36));
        secretKey.setCreateTime(new Date());
        return secretKeyService.save(secretKey);
    }

    @PostMapping()
    public int update(@RequestBody SecretKey secretKey) {
        return secretKeyService.update(secretKey);
    }

    @PostMapping("bind")
    public int bind(@RequestBody DeviceBind deviceBind) {
        return secretKeyService.bind(deviceBind);
    }
}
